<template>
  <el-dialog
    :model-value="visible"
    :title="dialogTitle"
    width="60%"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :disabled="isViewMode"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="演出标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入演出标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="艺人" prop="artistId">
            <el-select v-model="form.artistId" placeholder="请选择艺人" filterable style="width: 100%;">
              <el-option
                v-for="artist in artistList"
                :key="artist.id"
                :label="artist.name"
                :value="artist.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="演出描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入演出描述"
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="场地" prop="venueId">
            <el-select 
              v-model="form.venueId" 
              placeholder="请选择场地" 
              filterable 
              style="width: 100%;"
              @change="handleVenueChange"
            >
              <el-option
                v-for="venue in venueList"
                :key="venue.id"
                :label="venue.name"
                :value="venue.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="楼层" prop="floorId">
            <el-select 
              v-model="form.floorId" 
              placeholder="请选择楼层" 
              filterable 
              style="width: 100%;"
              :disabled="!form.venueId"
            >
              <el-option label="不指定楼层" :value="0" />
              <el-option
                v-for="floor in floorList"
                :key="floor.id"
                :label="floor.name"
                :value="floor.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最大容量" prop="maxCapacity">
            <el-input-number v-model="form.maxCapacity" :min="0" placeholder="不填则不限制" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
              <el-option label="已安排" value="SCHEDULED" />
              <el-option label="进行中" value="ONGOING" />
              <el-option label="已完成" value="COMPLETED" />
              <el-option label="已取消" value="CANCELLED" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">{{ isViewMode ? '关闭' : '取消' }}</el-button>
        <el-button v-if="!isViewMode" type="primary" @click="handleSubmit">
          {{ isCreateMode ? '创建' : '保存' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { performanceApi, artistApi, venueApi, floorApi } from '@/api'
import type { Performance, Artist, Venue, Floor } from '@/types'

const props = defineProps<{
  visible: boolean
  mode: 'create' | 'edit' | 'view'
  performanceData: Performance | null
}>()

const emit = defineEmits(['close', 'success'])

const formRef = ref<FormInstance>()
const form = reactive<Partial<Performance>>({})
const artistList = ref<Artist[]>([])
const venueList = ref<Venue[]>([])
const floorList = ref<Floor[]>([])

const isCreateMode = computed(() => props.mode === 'create')
const isViewMode = computed(() => props.mode === 'view')

const dialogTitle = computed(() => {
  if (isCreateMode.value) return '添加演出'
  if (isViewMode.value) return '查看演出详情'
  return '编辑演出'
})

const rules = reactive<FormRules>({
  title: [{ required: true, message: '请输入演出标题', trigger: 'blur' }],
  artistId: [{ required: true, message: '请选择艺人', trigger: 'change' }],
  venueId: [{ required: true, message: '请选择场地', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
})

watch(
  () => props.performanceData,
  async (newData) => {
    if (newData) {
      Object.assign(form, newData)
      // 如果有场地ID，加载对应的楼层列表
      if (newData.venueId) {
        await fetchFloors(newData.venueId)
      }
    } else {
      Object.keys(form).forEach(key => delete form[key as keyof typeof form])
      // 重置楼层相关数据
      form.floorId = 0
      floorList.value = []
    }
  },
  { immediate: true, deep: true }
)

const fetchArtists = async () => {
  try {
    const response = await artistApi.getList({ page: 1, limit: 1000 }) // 获取所有艺人
    artistList.value = response.data.data
  } catch (error) {
    ElMessage.error('获取艺人列表失败')
  }
}

const fetchVenues = async () => {
  try {
    const response = await venueApi.getList({ page: 1, limit: 1000 }) // 获取所有场地
    venueList.value = response.data.data
  } catch (error) {
    ElMessage.error('获取场地列表失败')
  }
}

const fetchFloors = async (venueId?: number) => {
  if (!venueId) {
    floorList.value = []
    return
  }
  
  try {
    const response = await floorApi.getByVenue(venueId)
    floorList.value = response.data || []
  } catch (error) {
    ElMessage.error('获取楼层列表失败')
    floorList.value = []
  }
}

const handleVenueChange = async (venueId: number) => {
  // 清空楼层选择
  form.floorId = 0
  // 获取对应场地的楼层列表
  await fetchFloors(venueId)
}

const handleClose = () => {
  emit('close')
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备提交数据
        const submitData = { ...form }
        
        // 如果楼层ID为0（不指定楼层），则设置为undefined
        if (submitData.floorId === 0) {
          submitData.floorId = undefined
        }
        
        if (isCreateMode.value) {
          let data = await performanceApi.create(submitData as Performance)
          console.log(data)
          ElMessage.success('创建成功')
        } else {
          let data = await performanceApi.update(submitData.id!, submitData as Performance)
          console.log(data)
          ElMessage.success('更新成功')
        }
        emit('success')
      } catch (error) {
        ElMessage.error(isCreateMode.value ? '创建失败' : '更新失败')
      }
    }
  })
}

onMounted(() => {
  fetchArtists()
  fetchVenues()
  fetchFloors()
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>